import {
    Form,
    Button,
    Card,
    Breadcrumb,
    Radio,
    DatePicker,
    Tag,
    Image,
    Modal,
    message,
} from "antd";
import { Link, useHistory } from "react-router-dom";
import styles from "./index.module.scss";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { Table, Space } from "antd";
import { useDispatch } from "react-redux";
import { useEffect } from "react";
import { delArticle, getArticles } from "@/store/actions";
import { useSelector } from "react-redux";
// 默认图片
import defaultImg from "@/assets/error.png";
import { useRef } from "react";
import Channel from "@/components/Channel";
// 阅读状态数据（不同状态文字和颜色不一样）
const statusLabel = [
    { text: "草稿", color: "default" },
    { text: "待审核", color: "blue" },
    { text: "审核通过", color: "green" },
    { text: "审核拒绝", color: "red" },
];

const Article = () => {
    // 设置每一列的标题和表头title dataIndex数据字段
    const columns = [
        {
            title: "封面",
            dataIndex: "cover",
            key: "cover",
            render: () => (
                <Image
                    src={defaultImg}
                    style={{ objectFit: "cover" }}
                    width={200}
                    height={120}
                />
            ),
        },
        {
            title: "标题",
            dataIndex: "title",
            key: "title",
        },
        {
            title: "状态",
            dataIndex: "status",
            key: "status",
            render: (status) => {
                const info = statusLabel[status];
                return <Tag color={info.color}>{info.text}</Tag>;
            },
        },
        {
            title: "发布时间",
            dataIndex: "pubdate",
            key: "pubdate",
        },
        {
            title: "阅读数",
            dataIndex: "read_count",
            key: "read_count",
        },
        {
            title: "评论数",
            dataIndex: "comment_count",
            key: "comment_count",
        },
        {
            title: "点赞数",
            dataIndex: "like_count",
            key: "like_count",
        },
        {
            title: "操作",
            key: "action",
            render: (text, record) => (
                <Space size="middle">
                    <Button
                        onClick={() => editArticleFn(record.id)}
                        type="link"
                        icon={<EditOutlined />}
                    />
                    <Button
                        onClick={() => delArticleFn(record.id)}
                        type="link"
                        icon={<DeleteOutlined />}
                    />
                </Space>
            ),
        },
    ];
    const dispatch = useDispatch();
    useEffect(() => {
        // 得到文章数据
        dispatch(getArticles(params.current));
    }, [dispatch]);
    // 需要的参数
    const params = useRef({
        status: undefined,
        channel_id: undefined,
        begin_pubdate: undefined,
        end_pubdate: undefined,
        page: 1,
        per_page: 20,
    });
    const { results, total_count, page, per_page } = useSelector(
        (state) => state.article
    );
    // 筛选相关逻辑
    const onFinish = (values) => {
        // 对筛选参数进行处理
        params.current.status = values.status;
        params.current.channel_id = values.channel_id;
        if (values.dateArr) {
            // 日期数据默认是moment对象
            params.current.begin_pubdate = values.dateArr[0].format(
                "YYYY-MM-DD HH:mm:ss"
            );
            params.current.end_pubdate = values.dateArr[1].format(
                "YYYY-MM-DD HH:mm:ss"
            );
        } else {
            params.current.begin_pubdate = undefined;
            params.current.end_pubdate = undefined;
        }
        // 需要回到第一页
        params.current.page = 1;
        // 分发action发请求更新数据
        dispatch(getArticles(params.current));
    };
    // 分页逻辑
    const onPageChange = (page, pageSize) => {
        // 准备分页参数
        params.current.page = page;
        params.current.per_page = pageSize;
        // 分发action发请求更新数据
        dispatch(getArticles(params.current));
    };
    // 删除
    const delArticleFn = (id) => {
        Modal.confirm({
            title: "您是否确认删除该文章？",
            cancelText: "取消",
            okText: "确认",
            onOk: async () => {
                await dispatch(delArticle(id));
                await dispatch(getArticles(params.current));
                message.success("删除成功");
            },
        });
    };
    // 编辑跳转
    const history = useHistory();
    const editArticleFn = (id) => {
        history.push(`/publish/${id}`);
    };
    return (
        <div className={styles.root}>
            <Card
                title={
                    // 面包屑
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <Link to="/">首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>内容管理</Breadcrumb.Item>
                    </Breadcrumb>
                }>
                {/* 表单 */}
                <Form onFinish={onFinish}>
                    <Form.Item label="状态：" name="status">
                        <Radio.Group>
                            <Radio value={undefined}>全部</Radio>
                            <Radio value={0}>草稿</Radio>
                            <Radio value={1}>待审核</Radio>
                            <Radio value={2}>已通过</Radio>
                            <Radio value={3}>已拒绝</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="频道：" name="channel_id">
                        <Channel width={288} />
                    </Form.Item>
                    <Form.Item label="日期：" name="dateArr">
                        <DatePicker.RangePicker />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            筛选
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
            <Card
                title={`根据筛选条件共查询到 ${total_count} 条结果：`}
                style={{ marginTop: 24 }}>
                <Table
                    columns={columns}
                    dataSource={results}
                    rowKey="id"
                    pagination={{
                        current: page,
                        pageSize: per_page,
                        total: total_count,
                        onChange: onPageChange,
                    }}
                />
            </Card>
        </div>
    );
};

export default Article;
